﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ContractorTimesheet.DataModel;
using ContractorTimesheet.Infrastructure;
using ContractorTimesheet.Models;
using ContractorTimesheet.Repository;
using SimpleCrypto;

namespace ContractorTimesheet.Controllers
{
    public class ChangePasswordController : Controller
    {
        private UserRepository userRepository = new UserRepository();

        public ActionResult Index()
        {
            if (CurrentSession.User == null)
                return RedirectToAction("Login", "Home");

            return View(new ChangePasswordModel());
        }

        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            User user = CurrentSession.User;

            PBKDF2 crypto = new PBKDF2();

            if (user.Password == crypto.Compute(model.OldPassword, user.PasswordSalt))
            {
                user.Password = crypto.Compute(model.NewPassword);
                user.PasswordSalt = crypto.Salt;
                userRepository.UpdateUser(user);
                CurrentSession.User = user;
                model.Message = "Password changed successfully.";
            }
            else
            {
                model.Message = "Invalid Old Password.";
            }

            return Json(model);
        }

    }
}